package club.babyf.nativeai.demo.algorithm;

import java.util.ArrayList;
import java.util.List;

/**
 * _28_MergeKAscListNode.
 *
 * @author zhanglei.
 * @date 2025/8/8 20:53.
 * @description 合并K个正序链表为一个正序链表.
 */
public class _28_MergeKAscListNode {

    public static class ListNode {

        int val;

        ListNode next;

        public ListNode(int val) {
            this.val = val;
        }

        public ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }

        @Override
        public String toString() {
            StringBuilder sb = new StringBuilder();
            ListNode current = this;
            while (current != null) {
                sb.append(current.val);
                ListNode next = current.next;
                if (next != null) {
                    sb.append(" -> ");
                }
                current = next;
            }
            return sb.toString();
        }

    }

    public ListNode mergeKAscListNode(ListNode[] listNodes) {
        if (listNodes == null || listNodes.length == 0) {
            return null;
        }
        List<ListNode> currentList = new ArrayList<>();
        for (ListNode listNode : listNodes) {
            if (listNode != null) {
                currentList.add(listNode);
            }
        }
        if (currentList.isEmpty()) {
            return null;
        }
        while (currentList.size() > 1) {
            List<ListNode> mergeList = new ArrayList<>();
            for (int i = 0; i < currentList.size(); i+=2) {
                ListNode l1 = currentList.get(i);
                ListNode l2 = (i + 1) < currentList.size() ? currentList.get(i + 1) : null;
                ListNode listNode = mergeTwoAscListNode(l1, l2);
                mergeList.add(listNode);
            }
            currentList = mergeList;
        }
        return currentList.get(0);
    }

    private ListNode mergeTwoAscListNode(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(0);
        ListNode pre = dummy;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                pre.next = new ListNode(l1.val);
                l1 = l1.next;
            } else {
                pre.next = new ListNode(l2.val);
                l2 = l2.next;
            }
            pre = pre.next;
        }
        pre.next = (l1 != null) ? l1 : l2;
        return dummy.next;
    }

    public static void main(String[] args) {
        _28_MergeKAscListNode mergeKAscListNode = new _28_MergeKAscListNode();
        ListNode l1 = new ListNode(1, new ListNode(2, new ListNode(3)));
        ListNode l2 = new ListNode(1, new ListNode(2, new ListNode(3)));
        ListNode l3 = new ListNode(1, new ListNode(2, new ListNode(3)));
        ListNode listNode = mergeKAscListNode.mergeKAscListNode(new ListNode[]{l1, l2, l3});
        System.out.println(listNode);
    }

}
